package com.dongdongshop.util;

import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.google.gson.Gson;
import org.springframework.stereotype.Controller;

import java.util.Map;
import java.util.Random;

@Controller
public class SmsUtil {

/*    @Value("${aliyun.sms.template_code}")
    private String template_code;

    @Value("${aliyun.sms.sign_name}")
    private String sign_name;*/


    // 设置鉴权参数，初始化客户端
    private static DefaultProfile profile = DefaultProfile.getProfile(
            "cn-qingdao",// 地域ID
            "LTAI4G8zAa4LShzSP2zvukLt",// 您的AccessKey ID
            "M6HTIlA7QCtWvUxgyiNj0bUBYrRJ14");// 您的AccessKey Secret
    private static IAcsClient client = new DefaultAcsClient(profile);

    private static void log_print(String functionName, Object result) {
        Gson gson = new Gson();
        System.out.println("-------------------------------" + functionName + "-------------------------------");
        System.out.println(gson.toJson(result));
    }

/*    public static void main(String[] args) throws ClientException {


        sendSms("15189497653","666666");
    }*/

    /**
     * 发送短信
     */
    public String sendSms(String phoneNumber) throws ClientException {
        Random random = new Random();
        //生成0-9以内的6位数验证码
        String str="";
        for (int i=0;i<6;i++) {
            str += random.nextInt(10);
        }

        CommonRequest request = new CommonRequest();
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        // 接收短信的手机号码
        request.putQueryParameter("PhoneNumbers", phoneNumber);
        // 短信签名名称。请在控制台签名管理页面签名名称一列查看（必须是已添加、并通过审核的短信签名）。
        request.putQueryParameter("SignName", "东科创想");
        // 短信模板ID
        request.putQueryParameter("TemplateCode", "SMS_189714105");
        // 短信模板变量对应的实际值，JSON格式。
        request.putQueryParameter("TemplateParam", "{\"sms_code\":\""+str+"\"}");
        CommonResponse commonResponse = client.getCommonResponse(request);
        String data = commonResponse.getData();
        String sData = data.replaceAll("'\'", "");
        log_print("sendSms", sData);

        Gson gson = new Gson();
        String json = gson.toJson(sData);

        Map map = gson.fromJson(sData, Map.class);
        Object bizId = map.get("BizId");
        return str;
    }

}
